/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.purpose.bean.ContributoryRealityDetailBean;
import com.koron.purpose.service.api.UsingStandBookService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "usingStandBook", description = "使用台账")
@RestController
@RequestMapping("/usingStandBook")
public class UsingStandBookController {
    private final static  Logger logger = LoggerFactory.getLogger(UsingStandBookController.class);

    @Autowired
    private UsingStandBookService usingStandBookService;

    @ApiOperation("列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "manager", value = "单位code",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "keyword", value = "关键词",  dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页",  dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数",  dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryForList.htm", method = RequestMethod.GET)
    public MessageBean queryForList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String corpCode, @ApiIgnore Integer year, @ApiIgnore String manager,
                                    @ApiIgnore String keyword,@ApiIgnore Integer page, @ApiIgnore Integer pageSize) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return usingStandBookService.queryForList(corpCode, year, manager, page, pageSize,keyword);
    }

    @ApiOperation("根据ID查询使用台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/queryById.htm", method = RequestMethod.GET)
    public MessageBean queryById(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String id) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        return usingStandBookService.queryById(id);
    }

    @ApiOperation("保存使用台账(草稿)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "planId", value = "投入计划ID", required = true, paramType = "query", dataType = "String"),
            /*@ApiImplicitParam(name = "realityDetails", value = "实际投入明细JSON数组 对象,如：[{'id':'id','contributoryPlanId':'投入计划id'," +
                    "'detailId':'投入计划明细id','contributoryDetail':'投入明细'," +
                    "'time':'实际投入时间（yyyy-MM-dd HH:mm:ss）','realityMoney':'实际金额'," +
                    "'effectAppraisal':'效果评估','personCharge':'责任人'," +
                    "'personChargeName':'责任人名称','remark':'备注'," +
                    "'file':附件对象,'statusFlag':'状态标记(0-草稿 1-保存)'}]",  paramType = "query", dataType = "String")*/
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存", businessModule = "安全投入", businessManipulation = BusinessManipulation.OTHER)
    public MessageBean save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                            @ApiIgnore String planId, ContributoryRealityDetailBean realityDetailBean) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }    // 状态标记(0-草稿 1-保存)
        String statusFlag = "0";
        return usingStandBookService.save(user, planId, statusFlag, realityDetailBean, null);
    }

    @ApiOperation("保存使用台账(保存)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "planId", value = "投入计划ID", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "personCode", value = "审批人code", required = true, paramType = "query", dataType = "String")
            /*@ApiImplicitParam(name = "realityDetails", value = "实际投入明细JSON数组 对象,如：[{'id':'id','contributoryPlanId':'投入计划id'," +
                    "'detailId':'投入计划明细id','contributoryDetail':'投入明细'," +
                    "'time':'实际投入时间（yyyy-MM-dd HH:mm:ss）','realityMoney':'实际金额'," +
                    "'effectAppraisal':'效果评估','personCharge':'责任人'," +
                    "'personChargeName':'责任人名称','remark':'备注'," +
                    "'file':附件对象,'statusFlag':'状态标记(0-草稿 1-保存)'}]", required = false)*/
    })
    @RequestMapping(value = "/submit.htm", method = RequestMethod.POST)
    @Log(title = "提交", businessModule = "安全投入", businessManipulation = BusinessManipulation.OTHER)
    public MessageBean submit(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                              @ApiIgnore String planId, ContributoryRealityDetailBean realityDetailBean,
                              @ApiIgnore String personCode) {
        if (null == user) {
            MessageBean<?> msg = new MessageBean<>();
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        // 状态标记(0-草稿 1-保存)
        String statusFlag = "1";
        return usingStandBookService.save(user, planId, statusFlag, realityDetailBean, personCode);
    }

    @ApiOperation("导出使用台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "year", value = "年份",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "manager", value = "单位code",  paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/exportUsingStandBook.htm", method = RequestMethod.GET)
    @Log(title = "导出使用台账", businessModule = "安全投入", businessManipulation = BusinessManipulation.EXPORT)
    public HttpEntity<?> exportUsingStandBook(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore String corpCode, @ApiIgnore Integer year, @ApiIgnore String manager) {
        if (null == user) {
            return null;
        }
        List<Map> list = usingStandBookService.exportQueryForList(corpCode, year, manager);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File file = new File("static/excel/UsingStandBookExport.xlsx");
        try (
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/excel/UsingStandBookExport.xlsx");
        ) {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("使用台账", file, "UsingStandBookExport.btl", map);
    }
}
